import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:katana_router/katana_router.dart';
import 'package:thal/backstage/blueprint/group_chat_print.dart';
import 'package:thal/backstage/blueprint/user_print.dart';
import 'package:thal/backstage/control_room/global_state_provider.dart';
import 'package:thal/backstage/control_room/group_chat_room.dart';
import 'package:thal/backstage/control_room/user_room.dart';
import 'package:thal/backstage/toolkit/utilities/asset_manifest.dart';
import 'package:thal/backstage/toolkit/utilities/color_palette.dart';
import 'package:thal/backstage/toolkit/utilities/dimension_rules.dart';
import 'package:thal/backstage/toolkit/widgets/report_focus_curtain.dart';

part 'group_detail_production.page.dart';

/// 群聊详情页面
@PagePath('/group-detail/:groupId')
class GroupDetailProduction extends StatefulWidget {
  final String groupId;

  const GroupDetailProduction({super.key, required this.groupId});

  @pageRouteQuery
  static RouteQuery query({required String groupId}) =>
      const _$GroupDetailProductionQuery().call(groupId: groupId);

  @override
  State<GroupDetailProduction> createState() => _GroupDetailProductionState();
}

class _GroupDetailProductionState extends State<GroupDetailProduction> {
  late final TextEditingController _contentController;
  late final GroupChatRoom _groupChatRoom;
  late final UserRoom _userRoom;

  @override
  void initState() {
    super.initState();
    _contentController = TextEditingController();
  }

  @override
  void dispose() {
    _contentController.dispose();
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _groupChatRoom = GlobalStateProvider.groupChatRoomOf(context);
    _userRoom = GlobalStateProvider.userRoomOf(context);
  }

  /// 发送消息
  void _postMessage() {
    final content = _contentController.text.trim();
    if (content.isEmpty) return;

    final currentUser = _userRoom.fetchCurrentUser();
    if (currentUser == null) return;

    _groupChatRoom.sendGroupMessage(widget.groupId, currentUser.id, content);

    _contentController.clear();
  }

  /// 处理举报群聊
  void _reportGroupChat(String groupId) {
    final currentUser = _userRoom.fetchCurrentUser();
    if (currentUser == null) return;

    ReportAccusation.raise(
      context,
      targetId: groupId,
      targetType: 'group_chat',
      onReportSubmitted: (reason) {
        // 删除群聊中的所有消息
        _groupChatRoom.deleteGroupChat(groupId);
        // 返回上一个页面
        Navigator.of(context).pop();
      },
    );
  }

  /// 获取稳定的在线状态
  bool _getStableOnlineStatus(String userId) {
    final hashCode = userId.hashCode;
    return hashCode % 3 != 0;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Color(0xFFD0EEF9), Color(0xFFE0F5FC)],
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Stack(
            children: [
              // 主要内容区域
              Column(
                children: [
                  // 顶部标题栏
                  _buildTitleBar(context),
                  // 消息列表
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 16.w),
                      child: Observer(
                        builder:
                            (_) => Container(
                              padding: EdgeInsets.symmetric(horizontal: 15.h),
                              decoration: BoxDecoration(
                                color: ColorPalette.white,
                                borderRadius: BorderRadius.only(
                                  topLeft: Radius.circular(26.r),
                                  topRight: Radius.circular(26.r),
                                ),
                              ),
                              child: _buildConversationList(context),
                            ),
                      ),
                    ),
                  ),
                  85.h.heightBox, // 为底部输入框留空间
                ],
              ),
              // 底部输入框
              Positioned(
                left: 0,
                right: 0,
                bottom: 0,
                child: _buildTextField(context),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部标题栏
  Widget _buildTitleBar(BuildContext context) {
    final currentUser = _userRoom.fetchCurrentUser();
    final group = _groupChatRoom.fetchGroupChatById(widget.groupId);

    if (group == null || currentUser == null) {
      return SizedBox.shrink();
    }

    return Container(
      padding: EdgeInsets.symmetric(vertical: 16.h, horizontal: 16.w),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: ColorPalette.iconBg,
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.chevron_left_rounded,
                color: ColorPalette.black,
                size: 36.sp,
              ),
            ),
          ),
          36.w.widthBox,

          // 群聊名称
          Expanded(
            child: Center(
              child: Text(group.title, maxLines: 1)
                  .fontSize(17.sp)
                  .textColor(ColorPalette.black)
                  .arimo(weight: FontWeight.w700),
            ),
          ),

          // 举报按钮
          GestureDetector(
            onTap: () {
              _reportGroupChat(group.id);
            },
            child: Container(
              width: 40.w,
              height: 40.w,
              padding: EdgeInsets.all(8.w),
              decoration: BoxDecoration(
                color: ColorPalette.iconBg,
                shape: BoxShape.circle,
              ),
              child: Image.asset(
                AssetManifest.report2,
                width: 24.w,
                height: 24.w,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建消息列表
  Widget _buildConversationList(BuildContext context) {
    final currentUser = _userRoom.fetchCurrentUser();
    final group = _groupChatRoom.fetchGroupChatById(widget.groupId);

    if (group == null || currentUser == null) {
      return SizedBox.shrink();
    }

    final messages = _groupChatRoom.fetchGroupMessages(widget.groupId);

    if (messages.isEmpty) {
      return Center(
        child:
            Text('No messages yet')
                .fontSize(14.sp)
                .textColor(ColorPalette.black.withValues(alpha: 0.6))
                .arimo(),
      );
    }

    return ListView.builder(
      reverse: false,
      padding: EdgeInsets.only(top: 16.h, bottom: 16.h),
      itemCount: messages.length,
      itemBuilder: (context, index) {
        final message = messages[index];
        final isFromCurrentUser = message.userId == currentUser.id;

        return Padding(
          padding: EdgeInsets.only(bottom: 16.h),
          child: _buildMessageItem(message, isFromCurrentUser, currentUser),
        );
      },
    );
  }

  /// 构建消息气泡
  Widget _buildMessageItem(
    GroupChatMessagePrint message,
    bool isFromCurrentUser,
    UserPrint currentUser,
  ) {
    // 获取发送者信息
    final sender = _userRoom.fetchUserById(message.userId);

    if (isFromCurrentUser) {
      // 当前用户发送的消息（右侧，蓝色）
      return Align(
        alignment: Alignment.centerRight,
        child: ConstrainedBox(
          constraints: BoxConstraints(maxWidth: 230.w),
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
            decoration: BoxDecoration(
              color: ColorPalette.blue3,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(10.r),
                topRight: Radius.circular(10.r),
                bottomLeft: Radius.circular(10.r),
                bottomRight: Radius.zero, // 右下角直角
              ),
            ),
            child: Text(message.content, style: TextStyle(height: 1.83))
                .fontSize(14.sp)
                .textColor(ColorPalette.blue1)
                .arimo(weight: FontWeight.w400),
          ),
        ),
      );
    } else {
      // 其他成员发送的消息（左侧，白色，带头像）
      return Align(
        alignment: Alignment.centerLeft,
        child: Row(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            // 头像和在线状态
            Stack(
              alignment: Alignment.bottomRight,
              children: [
                Container(
                  width: 40.w,
                  height: 40.w,
                  decoration: BoxDecoration(shape: BoxShape.circle),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(20.r),
                    child: Image.asset(
                      sender?.avatar ?? AssetManifest.avatar1,
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                // 在线状态指示器
                Container(
                  width: 12.w,
                  height: 12.w,
                  decoration: BoxDecoration(
                    color:
                        sender != null
                            ? (_getStableOnlineStatus(sender.id)
                                ? Colors.green
                                : Colors.grey)
                            : Colors.grey,
                    shape: BoxShape.circle,
                    border: Border.all(color: Colors.white, width: 2.w),
                  ),
                ),
              ],
            ),
            8.w.widthBox,
            // 消息气泡
            Flexible(
              child: ConstrainedBox(
                constraints: BoxConstraints(maxWidth: 230.w),
                child: Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 12.w,
                    vertical: 8.h,
                  ),
                  decoration: BoxDecoration(
                    color: const Color(0xFFF7F7F7),
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(10.r),
                      topRight: Radius.circular(10.r),
                      bottomLeft: Radius.zero, // 左下角直角
                      bottomRight: Radius.circular(10.r),
                    ),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 发送者名称
                      Text(
                            sender?.username ?? 'Unknown',
                            style: TextStyle(height: 1.2),
                          )
                          .fontSize(11.sp)
                          .textColor(ColorPalette.black.withValues(alpha: 0.6))
                          .arimo(weight: FontWeight.w600),
                      2.h.heightBox,
                      // 消息内容
                      Text(message.content, style: TextStyle(height: 1.83))
                          .fontSize(14.sp)
                          .textColor(const Color(0xFF333333))
                          .arimo(weight: FontWeight.w400),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    }
  }

  /// 构建输入框
  Widget _buildTextField(BuildContext context) {
    final currentUser = _userRoom.fetchCurrentUser();
    if (currentUser == null) return SizedBox.shrink();

    return SizedBox(
      height: 105.h,
      child: Stack(
        children: [
          // 背景图片
          Positioned.fill(
            child: Image.asset(
              AssetManifest.navigationBackground,
              fit: BoxFit.fill,
            ),
          ),
          // 输入框内容
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 32.h),
            child: Row(
              children: [
                // 输入框
                Expanded(
                  child: SizedBox(
                    height: 40.h,
                    child: TextField(
                      controller: _contentController,
                      textInputAction: TextInputAction.done,
                      decoration: InputDecoration(
                        hintText: 'Type here...',
                        hintStyle: TextStyle(
                          fontSize: 14.sp,
                          color: ColorPalette.black.withValues(alpha: 0.5),
                        ),
                        filled: true,
                        fillColor: Colors.transparent,
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(25.r),
                          borderSide: BorderSide(
                            color: const Color(0x99999999),
                            width: 1,
                          ),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(25.r),
                          borderSide: BorderSide(
                            color: const Color(0x99999999),
                            width: 1,
                          ),
                        ),
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: 16.w,
                          vertical: 10.h,
                        ),
                        suffixIcon: GestureDetector(
                          onTap: _postMessage,
                          child: Padding(
                            padding: EdgeInsets.all(8.w),
                            child: Image.asset(
                              AssetManifest.send,
                              width: 22.w,
                              height: 22.w,
                            ),
                          ),
                        ),
                      ),
                      style: TextStyle(fontSize: 14.sp),
                      maxLines: null,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
